package com.service.serviceImpl;

import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.apiresult.ResultCode;
import com.common.exception.BusinessException;
import com.system.entity.LoginUser;
import com.system.entity.User;
import com.system.mapper.RoleMapper;
import com.system.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author liuxuhuang
 * @date 2023年03月31日 23:20
 */
@Service(value = "userDetailServiceImpl")
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (StringUtils.isBlank(s)) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED);
        }
        User user = null;
        if (Validator.isEmail(s)) {
            user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail, s));
        } else {
            user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, s));
        }
        if (Objects.isNull(user)) {
            throw new BusinessException(ResultCode.USERNAMENOEXIST);
        }
        List<String> roleList = roleMapper.selectRoleList(user.getId());
        return new LoginUser(user, roleList);
    }
}
